import { deleteConfig, getTagConfigList, saveConfig } from '@/services/tag'
import { css } from '@emotion/css'
import { Breadcrumb, Button, Input, Tag, Tooltip } from 'antd'
import React, { useEffect, useRef, useState } from 'react'
import router from 'umi/router'
const EventType = (props) => {
  const [tags, setTags] = useState([])
  const [inputVisible, setInputVisible] = useState(false)
  const [inputValue, setInputValue] = useState('')
  const [editInputIndex, setEditInputIndex] = useState(-1)
  const [editInputValue, setEditInputValue] = useState('')
  const [dataSource, setDataSource] = useState()
  const inputRef = useRef(null)
  const editInputRef = useRef(null)
  const TagConfigList = async () => {
    const res = await getTagConfigList({ id: props.id })
    console.log(res)
    setDataSource(res.data)
    let tagsArr = []
    if (res.data) {
      tagsArr = res.data.map((item) => item.expressionValue)
    }
    setTags(res.data === null ? [] : tagsArr)
  }
  useEffect(() => {
    TagConfigList()
  }, [])
  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus()
    }
  }, [inputVisible])
  useEffect(() => {
    editInputRef.current?.focus()
  }, [inputValue])

  const handleClose = async (removedTag) => {
    const id = dataSource?.find((item) => item.expressionValue === removedTag).id
    const res = await deleteConfig({ ids: [id] })
    TagConfigList()
    // const newTags = tags.filter((tag) => tag !== removedTag)
    // console.log(newTags)
    // setTags(newTags)
  }

  const showInput = () => {
    setInputVisible(true)
  }

  const handleInputChange = (e) => {
    setInputValue(e.target.value)
  }

  const handleInputConfirm = async () => {
    if (inputValue && tags.indexOf(inputValue) === -1) {
      setTags([...tags, inputValue])
    }

    setInputVisible(false)
    const res = await saveConfig({ mappingId: props.id, expressionValue: inputValue })
    TagConfigList()
    setInputValue('')
  }

  const handleEditInputChange = (e) => {
    setEditInputValue(e.target.value)
  }

  const handleEditInputConfirm = () => {
    const newTags = [...tags]
    newTags[editInputIndex] = editInputValue
    setTags(newTags)
    setEditInputIndex(-1)
    setInputValue('')
  }
  return (
    <>
      <div
        style={{
          height: '50px',
          width: '100%',
          backgroundColor: '#ECEFF2',
          display: 'flex',
          alignItems: 'center',
        }}
      >
        <Breadcrumb>
          <Breadcrumb.Item>
            <a
              onClick={() => {
                router.push('/resource/organization/allOrganization')
              }}
            >
              标签管理
            </a>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <a
              onClick={() => {
                router.push('/resource/addOrganization')
              }}
            >
              配置
            </a>
          </Breadcrumb.Item>
        </Breadcrumb>
      </div>
      <h2
        style={{
          paddingLeft: '20px',
          height: '50px',
          lineHeight: '50px',
          marginBottom: '0px',
          borderBottom: '1px solid #ECEFF2',
        }}
      >
        触发词
      </h2>
      <div
        className={css`
          padding: 20px;
        `}
      >
        <Button
          style={{
            marginRight: '10px',
            marginBottom: '20px',
          }}
          type="primary"
          onClick={() => {
            setInputVisible(true)
          }}
          // icon={<PlusOutlined />}
        >
          新增
        </Button>
        <div style={{}}>
          {tags.map((tag, index) => {
            if (editInputIndex === index) {
              return (
                <Input
                  ref={editInputRef}
                  key={tag}
                  size="big"
                  value={editInputValue}
                  onChange={handleEditInputChange}
                  onBlur={handleEditInputConfirm}
                  onPressEnter={handleEditInputConfirm}
                />
              )
            }

            const isLongTag = tag.length > 20
            const tagElem = (
              <Tag
                color="green"
                className={css`
                  height: 30px;
                  lineheight: 30px;
                `}
                key={tag}
                closable
                onClose={() => handleClose(tag)}
              >
                <span>{isLongTag ? `${tag.slice(0, 20)}...` : tag}</span>
              </Tag>
            )
            return isLongTag ? (
              <Tooltip title={tag} key={tag}>
                {tagElem}
              </Tooltip>
            ) : (
              tagElem
            )
          })}
          {inputVisible && (
            <Input
              className={css`
                width: 150px;
                margin-right: 8px;
                vertical-align: top;
              `}
              placeholder="请输入触发词"
              ref={inputRef}
              type="text"
              size="big"
              value={inputValue}
              onChange={handleInputChange}
              onBlur={handleInputConfirm}
              onPressEnter={handleInputConfirm}
            />
          )}
          {/* {!inputVisible && (
            <Tag className="site-tag-plus" onClick={showInput}>
              <PlusOutlined /> New Tag
            </Tag>
          )} */}
        </div>
      </div>
    </>
  )
}
export default EventType
